import {_decorator, Camera, Component, EventTouch, Input, input, Node, Tween, UITransform, Vec2, Vec3} from 'cc';
import {GridSystemManage} from "db://assets/script/modules/GridSystemManage";
import {GameManager} from "db://assets/script/modules/GameManager";
import {SceneManager} from "db://assets/script/modules/SceneManager";

const {ccclass, property} = _decorator;

@ccclass('ClickMoveController')
export class ClickMoveController extends Component {

    playerNode: Node = null;
    gameCameraNode: Node = null;
    gridSize: number = 64; // 新增格子尺寸参数

    _moveTween: Tween;
    _pathQueue: Vec2[] = []; // 用于存储路径点的队列
    _targetNodePos: Vec3 = new Vec3(); // 用于存储路径点的队列

    start() {
        this.gridSize = GridSystemManage.gridSize
        this.playerNode = GameManager.playerNode
        this.gameCameraNode = GameManager.gameCameraNode
        input.on(Input.EventType.TOUCH_START, this.onTouchStart, this);
    }

    onDestroy() {
        input.off(Input.EventType.TOUCH_START, this.onTouchStart, this);
    }

    onTouchStart(event: EventTouch) {
        const touchPos = event.touch.getLocation()
        const uiPos = this.gameCameraNode.getComponent(Camera).screenToWorld(new Vec3(touchPos.x, touchPos.y));
        const pos = this.node.parent.getComponent(UITransform).convertToNodeSpaceAR(uiPos)
        const startPos = GridSystemManage.nodePosToGridPos(this.playerNode.getPosition())
        const endPos = GridSystemManage.nodePosToGridPos(pos).add2f(-1, -1)
        const list = GridSystemManage.findPath(startPos, endPos)
        // console.log(startPos, endPos)
        // console.log(list)

        // 如果路径为空，直接返回
        if (list.length === 0) {
            return;
        }

        // 将新路径点添加到队列中
        this._pathQueue = [...list];

        // 如果当前没有在移动，则开始移动
        if (!GameManager.isMoving) {
            this._startMove();
        }
    }

    _startMove() {
        if (this._pathQueue.length === 0) {
            GameManager.setIsMoving(false)
            return;
        }

        GameManager.setIsMoving(true)

        // 获取队列中的下一个路径点
        const targetGridPos = this._pathQueue.shift();
        const targetNodePos = GridSystemManage.gridPosToNodePos(targetGridPos);
        this._targetNodePos = targetNodePos.clone()
        // 使用tween实现平滑移动
        this._moveTween = new Tween(this.playerNode)
            .to(0.2, {position: targetNodePos}, {
                easing: 'linear',
                onUpdate: () => {
                    this.gameCameraNode.setPosition(this.playerNode.position);
                },
                onComplete: () => {
                    // 强制对齐网格中心
                    this.playerNode.setPosition(targetNodePos);
                    this._moveTween.destroySelf()
                    // 检查是否还有剩余路径点
                    if (this.checkGatewayAndGo()) {
                        this._pathQueue = []
                        GameManager.setIsMoving(false)
                    } else if (this._pathQueue.length > 0) {
                        this._startMove(); // 继续移动到下一个路径点
                    } else {
                        GameManager.setIsMoving(false)
                    }
                }
            })
            .start();
    }

    checkGatewayAndGo(): boolean {
        const gridPos = GridSystemManage.nodePosToGridPos(this.playerNode.getPosition());
        if (GridSystemManage.checkTargetIsGateway(gridPos)) {
            console.log('开始传送', GridSystemManage.getGatewayTarget(gridPos))
            const key: string = GridSystemManage.getGatewayTarget(gridPos)
            SceneManager.initMap(key)
            // 业务判断
            return true
        }

        // 默认没踩到传送
        return false
    }
}
